import { AsyncRoutes } from "./type"
import allView from '@/utils/glots';
/**
 * @param constantRoutes
 */
export function convertRouter(asyncRoutes: AsyncRoutes[]) {
  console.log(allView)
  return asyncRoutes.map((route) => {
    if (route.component) {
      if (route.component === 'Layout') {
        route.component = Object.values(import.meta.globEager('../layout/Index.vue'))[0].default
      } else if (route.component === 'EmptyLayout') {
        route.component = Object.values(import.meta.globEager('../layout/EmptyLayout.vue'))[0].default
      } else {
        const index = (route.component as string).indexOf('views')
        const path =
          index > 0 ? (route.component as string).slice(index) : `views/${route.component}`
        const apaths = `../${path}.vue`
        console.log(apaths, allView)
        route.component = allView[apaths].default
      }
    }
    if (route.children && route.children.length) { route.children = convertRouter(route.children) }
    if (route.children && route.children.length === 0) { delete route.children }
    return route
  })
}

/**
 * @param permissions
 * @param route
 */
function hasPermission(permissions: string[], route: AsyncRoutes) {
  if (route.meta && route.meta.permissions) {
    return permissions.some((role) => {
      if (route.meta && route.meta.permissions) {
        return route.meta.permissions.includes(role)
      }
      else {
        return false
      }
    })
  } else {
    return true
  }
}

/**
 * @param routes
 * @param permissions
 */
export function filterAsyncRoutes(routes: AsyncRoutes[], permissions: string[]) {
  const finallyRoutes: AsyncRoutes[] = []
  routes.forEach((route) => {
    const item = { ...route }
    if (hasPermission(permissions, item)) {
      if (item.children) {
        item.children = filterAsyncRoutes(item.children, permissions)
      }
      finallyRoutes.push(item)
    }
  })
  console.log(finallyRoutes)
  return finallyRoutes
}
